<template>
    <van-form ref="regForm" class="regForm" @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="LoginParams.loginname" name="tel" label="账号" placeholder="用户名/手机号"
                :rules="LoginRules.tel">
            </van-field>
            <van-field v-model="LoginParams.password" :type="passwordShow ? 'text' : 'password'" name="password" label="密码"
                placeholder="密码" :right-icon="passwordShow ? 'eye-o' : 'closed-eye'" @click-right-icon="onClickIcon"
                :rules="LoginRules.password">
            </van-field>
            <van-field>
                <template #label>
                    <router-link to="/reg" >去注册</router-link>
                </template>
                <template #button>
                    <router-link to="">忘记密码?</router-link>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                登录
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
    import { RouterLink, useRouter,useRoute } from 'vue-router';
    import { reactive, ref,} from 'vue';
    import {reg} from "@/utils/rules"
    import {useAuthStore} from "@/stores/auth"
    // import {doLoginAPI} from "@/api/user"
    import { showSuccessToast,showFailToast } from 'vant';


    const AuthStore = useAuthStore();
    const {loginAndUpdateAuth} = AuthStore;

    const router = useRouter();
    const route = useRoute();

    const LoginParams = reactive<LoginParamsRaw>({
        loginname: "17386141517",
        password: "123123aa",
    })

    const passwordShow = ref(false);

    const LoginRules = reactive<LoginRules>({
        tel: [
            { required: true, message: '请填写用户名/手机号', trigger: "onChange" },
            { pattern: reg.phone, message: '请填写正确的手机号', trigger: "onChange" },
        ],
        password: [
            { required: true, message: '请填写密码', trigger: "onChange" },
            { pattern: reg.pwd, message: '请输入6-16位的数字加字母', trigger: "onChange" },
        ]
    })

    const onClickIcon = () => {
        passwordShow.value = !passwordShow.value;
    }


    const onSubmit =async ()=>{
        try{
            let result = await loginAndUpdateAuth(LoginParams)
            showSuccessToast("登录成功");

            let {ReturnUrl} = route.query;
            if(ReturnUrl){
                router.push(ReturnUrl as string);
            }else{
                router.push("/");
            }

        }catch(err:any){
            showFailToast(err.message);
        }
    }


</script>

<style lang="scss" scoped>

    #van-field-4-label{
        color:red;
    }
    .regForm {
        margin-top: 50px;
    }

</style>